/* Vexredus Tracker
 * Version: Beta 1.0
 * Written by: David Steenari 
 * Contact: david [at] steenari [dot] com
 * 
 * Copyright (c) 2012 David Steenari.
 * All rights reserved. 
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *    This product includes software developed by David Steenari.
 * 4. Neither the name of the Vexredus Tracker nor the
 *    names of its contributors may be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY DAVID STEENARI ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL DAVID STEENARI BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

// the FIXME list:
// FIXME Bug: when loaded file then picking other, but pressing cancel: Keep getting cantreadfile

// LocalFile Global variables
var log_f; 
var guided_f;
var flightPlan_f;
var boundary_f;

var log_poll_t = 1000; // Log file polling time period in ms
var guided_poll_t = 5000; // Guided file polling time period in ms
var flightPlan_poll_t = 10000; // Flight plan file polling time period in ms 
var boundary_poll_t = 10000; 
var homebase_poll_t = 5000; 

var interval_id_log_poll;
var interval_id_guided_poll;
var interval_id_flightPlan_poll;
var interval_id_boundary_poll;
var interval_id_homebase_poll;

// Data logic 
var log_latest_i = 0; // Latest read position index in log file 
var flightPlan_latest_i = 0;
var boundary_latest_i = 0;

// GUI global variabless
var map; // Google map canvas

// Paths to plot
var path_log; // Flight path to plot
var path_flightPlan; // Flight plan to plot
var path_etag; // ETAG path to plot

// GUI logic 
var gui_setWPClicked = false;

// Markers
var marker_uav; // Current position of UAV
var marker_clicked; // User selected next waypoint
var marker_guided; // Guided WP


//var pos_kiruna = new google.maps.LatLng(67.85, 20.216667);
var pos_esrange = new google.maps.LatLng(67.8917, 21.0817);
var pos_uav = pos_esrange;
var pos_homebase = new google.maps.LatLng(67.8917, 21.0817); // FIXME set before flight
var pos_mid_safety_box = new google.maps.LatLng(67.8880656,21.0848543);

var radius_boundarybox = 0; // in [m], boundary box radius
var radius_launchbox = 0; // in [m], launch box radius
var radius_safetybox = 0; // in [m], safety box radius
var radius_waypoint = 0; // in [m], waypoint radius for flightplan

var boundaryboxCircle;
var launchboxCircle;
var safetyboxCircle;

var wpCircleList = new Array();


// ****************************** Vexredus Parse_...() functions **************************************

function Parse_LogFile(logFileText) {
	//alert("DEBUG: Parse_LogFile()" + '\n' + logFileText);	

	var data_rows = logFileText.split("\n");

	// Loop through rows in file 
	for(var i=0; i<data_rows.length; i++) {
		var data_vars = data_rows[i].split(",");
		//alert("Lat: " + data_vars[1] + " Long: " + data_vars[2]); 
			
		var msg_i = parseFloat(data_vars[0]);
		// Only add new data
		if(msg_i > log_latest_i) {
			log_latest_i = msg_i; 
			document.getElementById('latest_msg_id').value = data_vars[0];
			var lat = parseFloat(data_vars[1]);
			var lng = parseFloat(data_vars[2]);

			// Add new positon to the path_log
			GUI_PathAddPos(path_log, new google.maps.LatLng(lat,lng));
			pos_uav = new google.maps.LatLng(lat,lng);
			marker_uav.setPosition(new google.maps.LatLng(lat,lng));
			marker_uav.setMap(map);
		}
	}

}

function Parse_GuidedFile(guidedFileText) {
	//alert("DEBUG: Parse_GuidedFile()" + '\n' + guidedFileText);	
	var data_rows = guidedFileText.split("\n");

	var data_vars = data_rows[0].split(",");
	//alert("Lat: " + data_vars[0] + " Long: " + data_vars[1]); 
			
	var lat = parseFloat(data_vars[0]);
	var lng = parseFloat(data_vars[1]);

	marker_guided.setPosition(new google.maps.LatLng(lat,lng));
}

function Parse_HomebaseFile(homebaseFileText) {
	//alert("DEBUG: Parse_HomebaseFile()" + '\n' + homebaseFileText);	
	var data_rows = homebaseFileText.split("\n");

	var data_vars = data_rows[0].split(",");
	//alert("Lat: " + data_vars[0] + " Long: " + data_vars[1]); 
			
	var lat = parseFloat(data_vars[0]);
	var lng = parseFloat(data_vars[1]);

	pos_homebase = new google.maps.LatLng(lat,lng);
	boundaryboxCircle.setCenter(pos_homebase);
	launchboxCircle.setCenter(pos_homebase);
	safetyboxCircle.setCenter(pos_mid_safety_box);
}

function Parse_FlightPlanFile(flightPlanFileText) {
	//alert("DEBUG: Parse_FlightPlanFile()" + '\n' + flightPlanFileText);	

	var data_rows = flightPlanFileText.split("\n");

	// Loop through rows in file 
	for(var i=0; i<data_rows.length; i++) {
		var data_vars = data_rows[i].split(",");
		//alert("Lat: " + data_vars[1] + " Long: " + data_vars[2]); 
			
		var msg_i = parseFloat(data_vars[0]);
		// Only add new data
		if(msg_i > flightPlan_latest_i) {
			flightPlan_latest_i = msg_i; 
			//document.getElementById('latest_msg_id').value = data_vars[0];
			var lat = parseFloat(data_vars[1]);
			var lng = parseFloat(data_vars[2]);
			GUI_PathAddPosWithCircle(path_flightPlan, new google.maps.LatLng(lat,lng));
		}
	}

}

function Parse_BoundaryFile(boundaryFileText) {
	//alert("DEBUG: Parse_BoundaryFile()" + '\n' + boundaryFileText);	

	var data_rows = boundaryFileText.split("\n");

	// Loop through rows in file 
	for(var i=0; i<data_rows.length; i++) {
		var data_vars = data_rows[i].split(",");
		//alert("Lat: " + data_vars[1] + " Long: " + data_vars[2]); 
			
		var msg_i = parseFloat(data_vars[0]);
		// Only add new data
		if(msg_i > boundary_latest_i) {
			// First row is circles
			if (msg_i == 1) {
				//var lat = parseFloat(data_vars[1]);
				//var lng = parseFloat(data_vars[2]);
				//pos_homebase = new google.maps.LatLng(lat,lng);

				radius_boundarybox = parseInt(data_vars[3]); 
				radius_launchbox = parseInt(data_vars[4]);
				radius_safetybox = parseInt(data_vars[5]);
				radius_waypoint = parseInt(data_vars[6]);

				boundaryboxCircle.setRadius(radius_boundarybox);
				launchboxCircle.setRadius(radius_launchbox);
				safetyboxCircle.setRadius(radius_safetybox);

				boundaryboxCircle.setCenter(pos_homebase);
				launchboxCircle.setCenter(pos_homebase);
				safetyboxCircle.setCenter(pos_mid_safety_box);
			}
			else {
				boundary_latest_i = msg_i; 
				//document.getElementById('latest_msg_id').value = data_vars[0];
				var lat = parseFloat(data_vars[1]);
				var lng = parseFloat(data_vars[2]);

				// Add new positon to the path_log
				GUI_PathAddPos(path_etag, new google.maps.LatLng(lat,lng));
				marker_uav.setPosition(new google.maps.LatLng(lat,lng));
				marker_uav.setMap(map);
			}
		}
	}

}


// ****************************** Vexredus LocalFile_...() functions **************************************

function LocalFile_Init() {
	// Check that File APIs are present in browser
	if(!(window.File && window.FileReader && window.FileList && window.Blob)) {
		//alert('LocalFile_Init(): Warning: The File APIs are not fully supported by your browser.');
	}

	// Initialize LocalFile Controls 
	document.getElementById('logFileInput').addEventListener('change', LocalFile_OpenLog, false); 
	document.getElementById('guidedFileInput').addEventListener('change', LocalFile_OpenGuided, false);
	document.getElementById('flightPlanFileInput').addEventListener('change', LocalFile_OpenFlightPlan, false);
	document.getElementById('boundaryFileInput').addEventListener('change', LocalFile_OpenBoundary, false);
	document.getElementById('homebaseFileInput').addEventListener('change', LocalFile_OpenHomebase, false);
}

function LocalFile_ReadFile(fileObj, funcname) {
	// Check so that file could be loaded 
	if(fileObj) {
		// Init a FileReader
		var fr = new FileReader();
		fr.onload = function(file) {
			var contents = file.target.result;
			
			//alert("DEBUG: LocalFile_ReadFile(): contents = " + contents); 

			// Invoke choosen function
			funcname(contents);
		}

		fr.readAsText(fileObj); 
		return true;
	}
	else {
		return false; 
	}
}

function LocalFile_OpenLog(log_filelist) {
	// Get the first and only file from filelist
	log_f = log_filelist.target.files[0]; // Object File

	// Empty old stuff
	path_log.clear();
	log_latest_i = 0;
	document.getElementById('latest_msg_id').value = 0;
	clearInterval(interval_id_log_poll);

	// Start polling the file every few seconds
	interval_id_log_poll = window.setInterval(function() {
		// Read file and check errors, then parse. 
		if(!LocalFile_ReadFile(log_f, Parse_LogFile)) {
			//alert("LocalFile_OpenLog(): Error: Failed to load file."); 
		}
	}, log_poll_t); 
	
	// Call directly when loading file
	if(!LocalFile_ReadFile(log_f, Parse_LogFile)) {
		//alert("LocalFile_OpenLog(): Error: Failed to load file."); 
	}

}

function LocalFile_OpenGuided(guided_filelist) {
	// Get the first and only file from filelist
	guided_f = guided_filelist.target.files[0]; // Object File

	// Empty old stuff
	clearInterval(interval_id_guided_poll);

	// Start polling the file every few seconds
	interval_id_guided_poll = window.setInterval(function() {
		// Read file and check errors, then parse. 
		if(!LocalFile_ReadFile(guided_f, Parse_GuidedFile)) {
			//alert("LocalFile_OpenGuided(): Error: Failed to load file."); 
		}
	}, guided_poll_t); 

	// Call directly when loading file
	if(!LocalFile_ReadFile(guided_f, Parse_GuidedFile)) {
		//alert("LocalFile_OpenGuided(): Error: Failed to load file."); 
	}
}

function LocalFile_OpenHomebase(homebase_filelist) {
	// Get the first and only file from filelist
	homebase_f = homebase_filelist.target.files[0]; // Object File

	// Empty old stuff
	clearInterval(interval_id_homebase_poll);

	// Start polling the file every few seconds
	interval_id_homebase_poll = window.setInterval(function() {
		// Read file and check errors, then parse. 
		if(!LocalFile_ReadFile(homebase_f, Parse_HomebaseFile)) {
			//alert("LocalFile_OpenHomebase(): Error: Failed to load file."); 
		}
	}, homebase_poll_t); 

	// Call directly when loading file
	if(!LocalFile_ReadFile(guided_f, Parse_HomebaseFile)) {
		//alert("LocalFile_OpenHomebase(): Error: Failed to load file."); 
	}
}

function LocalFile_OpenFlightPlan(flightPlan_filelist) {
	// Get the first and only file from filelist
	flightPlan_f = flightPlan_filelist.target.files[0]; // Object File

	// Empty old stuff
	path_flightPlan.clear();
	flightPlan_latest_i = 0;
	clearInterval(interval_id_flightPlan_poll);

	//alert("DEBUG: wpCircleList.length == " + wpCircleList.length);
	// Empty list of circles
	while(wpCircleList.length>0) {
		var wp_temp = wpCircleList[0];//wpCircleList.shift();
		//wp_temp.setVisible(false);
		wp_temp.setMap(null);
		wpCircleList.shift();
	}
	//alert("DEBUG: wpCircleList.length == " + wpCircleList.length);

	// Start polling the file every few seconds
	interval_id_flightPlan_poll = window.setInterval(function() {
		// Read file and check errors, then parse. 
		if(!LocalFile_ReadFile(flightPlan_f, Parse_FlightPlanFile)) {
			//alert("LocalFile_OpenFlightPlan(): Error: Failed to load file."); 
		}
	}, flightPlan_poll_t); 

	// Call directly when loading file
	if(!LocalFile_ReadFile(flightPlan_f, Parse_FlightPlanFile)) {
		//alert("LocalFile_OpenFlightPlan(): Error: Failed to load file."); 
	}
}

function LocalFile_OpenBoundary(boundary_filelist) {
	//alert("DEBUG: LocalFile_OpenBoundary() called.");
	// Get the first and only file from filelist
	boundary_f = boundary_filelist.target.files[0]; // Object File

	// Empty old stuff
	path_etag.clear();
	boundary_latest_i = 0;
	clearInterval(interval_id_boundary_poll);

	// Start polling the file every few seconds
	interval_id_boundary_poll = window.setInterval(function() {
		// Read file and check errors, then parse. 
		if(!LocalFile_ReadFile(boundary_f, Parse_BoundaryFile)) {
			//alert("LocalFile_OpenBoundary(): Error: Failed to load file."); 
		}
	}, boundary_poll_t); 


	// Call directly when loading file
	if(!LocalFile_ReadFile(boundary_f, Parse_BoundaryFile)) {
		//alert("LocalFile_OpenBoundary(): Error: Failed to load file."); 
	}
}


// ************************************* HTTP Telemetry functions ************************************ 
// HTTP Access DEPRECATED
/*

// Initialization
function HTTPTelemetry_Init() {
	// Start the server polling
	window.setInterval(function() {
		HTTPTelemetry_GetData();
	}, 5000);
} 

function HTTPTelemetry_GetData() {
	// Initialize XML request object
	var xhr = null; 
	try {  
		xhr = new ActiveXObject('Msxml2.XMLHTTP');
	}
	catch (e) { 
		try {
			xhr = new ActiveXObject('Microsoft.XMLHTTP');
		}
		catch (e2) { 
			try {
				xhr = new XMLHttpRequest();
			}
			catch (e3) {  xhr = false;   }
		}
	}

	if(xhr == null || xhr == false) {
		alert("GetTelemetryData(): error: 1");
	}

	// Function to call when XML request state has changed
	xhr.onreadystatechange = function() {
		if(xhr.readyState == 4) {
			if(xhr.status == 200) {
				LogFileParse(xhr.responseText);
			}
			else {
				alert("GetTelemetryData(): Error code: " + xhr.status);
			}
		}
	};

	xhr.open("GET", "data.txt", true);
	xhr.send(null);
}*/

// ****************************** Google Maps API ************************************ 

// New UAV position
function GUI_PathAddPos(path, position) {
	path.push(position);
	//map.setCenter(position);
	//pos_uav = position;
	//marker_uav.position(pos_uav);
}

function GUI_PathAddPosWithCircle(path, position) {
	path.push(position);

	var wpCircleOptions = {
		strokeColor: "#FF0000",
		strokeOpacity: 1.0,
		strokeWeight: 4,
		fillColor: "#FF0000",
		fillOpacity: 0.25,
		map: map,
		center: position,
		radius: radius_waypoint, 
		clickable: false
	};
	var wpCircle = new google.maps.Circle(wpCircleOptions);
	wpCircleList.push(wpCircle);

	//map.setCenter(position);
	//pos_uav = position;
	//marker_uav.position(pos_uav);
}

// Map position control buttons
function GUI_ButtonPositionControl(controlDiv, map, marker, name, zoomlevel) {
	controlDiv.style.padding = '5px';

	var controlUI = document.createElement('div');
	controlUI.style.backgroundColor = 'white';
	controlUI.style.borderStyle = 'solid';
	controlUI.style.borderWidth = '2px';
	controlUI.style.cursor = 'pointer';
	controlUI.style.textAlign = 'center';
	controlUI.title = 'Click to set the map to position';
	
	controlDiv.appendChild(controlUI);

	var controlText = document.createElement('div');
	controlText.style.fontFamily = 'Arial, sans-serif';
	controlText.style.fontSize = '12px';
	controlText.style.paddingLeft = '4px';
	controlText.style.paddingRight = '4px';
	controlText.innerHTML = '<strong>' + name + '</strong>';

	controlUI.appendChild(controlText);

	google.maps.event.addDomListener(controlUI, 'click', function() { 
		//alert("Reached Checkpoint 1!");
		map.setCenter(marker_uav.getPosition()); 
		//alert("Reached Checkpoint 2!");
		map.setZoom(zoomlevel);
	});
}

// Get data button
/*function GUI_ButtonGetData(controlDiv, map) {
	controlDiv.style.padding = '5px';
	
	var controlUI = document.createElement('div');
	controlUI.style.backgroundColor = 'white';
	controlUI.style.borderStyle = 'solid';
	controlUI.style.borderWidth = '2px';
	controlUI.style.cursor = 'pointer';
	controlUI.style.textAlign = 'center';
	controlUI.title = 'Click to set the map to position';
	
	controlDiv.appendChild(controlUI);

	var controlText = document.createElement('div');
	controlText.style.fontFamily = 'Arial, sans-serif';
	controlText.style.fontSize = '12px';
	controlText.style.paddingLeft = '4px';
	controlText.style.paddingRight = '4px';
	controlText.innerHTML = '<strong>GetTelemetryData()</strong>';

	controlUI.appendChild(controlText);

	google.maps.event.addDomListener(controlUI, 'click', function() {
		HTTPTelemetry_GetData();
	});

}*/

// Initialize GUI buttons
function GUI_InitButtons() {
	// Add the Kiruna button
	/*var kirunaControlDiv = document.createElement('div');
	var kirunaControl = new ButtonPositionControl(kirunaControlDiv, map, pos_kiruna, 'Kiruna', 12);
	kirunaControlDiv.index = 1;
	map.controls[google.maps.ControlPosition.TOP_RIGHT].push(kirunaControlDiv);*/

	// Add the Esrange button
	/*var esrangeControlDiv = document.createElement('div');
	var esrangeControl = new GUI_ButtonPositionControl(esrangeControlDiv, map, pos_esrange, 'Esrange', 14);
	esrangeControlDiv.index = 1;
	map.controls[google.maps.ControlPosition.TOP_RIGHT].push(esrangeControlDiv);*/

	// Add the UAV button
	var uavControlDiv = document.createElement('div');
	var uavControl = new GUI_ButtonPositionControl(uavControlDiv, map, marker_uav, 'Vexredus UAV', 14);
	uavControlDiv.index = 1;
	map.controls[google.maps.ControlPosition.TOP_RIGHT].push(uavControlDiv);

	// Add the GetTelemetryData() button
	/*var getdataControlDiv = document.createElement('div');
	var getdataControl = new GUI_ButtonGetData(getdataControlDiv, map);
	getdataControlDiv.index = 1;
	map.controls[google.maps.ControlPosition.TOP_RIGHT].push(getdataControlDiv);*/
}

function GUI_InitMarkers() {
	// Guided icon
	var icon_guided = {
		path: google.maps.SymbolPath.CIRCLE,
		fillColor: "#0000FF",
		fillOpacity: "1.0",
		scale: 8
	};

	// Add Guided marker
	marker_guided = new google.maps.Marker({
		//position: pos_esrange, 
		title: "Guided", 
		icon: icon_guided,
		map: map
	});

	// UAV icon
	var icon_uav = {
		path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
		fillColor: "black",
		fillOpacity: "1.0",
		scale: 5
	};

	// Add UAV marker
	marker_uav = new google.maps.Marker({
		//position: pos_esrange,
		title: "Vexredus",
		//icon: icon_uav
		//map: map 
		visible: false
	});

	// Flight path
	/*var path_logCoordinates = [
		pos_esrange,
		new google.maps.LatLng(67.45, 21.67),
		new google.maps.LatLng(67.34, 21.12),
		new google.maps.LatLng(67.1, 21.23),
		new google.maps.LatLng(67.0, 21.0),
	];*/

	// LOGFILE path
	var path_logLine = new google.maps.Polyline({
		//path: path_logCoordinates,
		strokeColor: "#00FF00",
		strokeOpacity: 1.0,
		strokeWeight: 2,
		icons: [{
			icon: icon_uav,
			offset: '100%'
			}]
	});

	path_logLine.setMap(map);
	path_log = path_logLine.getPath();

	// For making the flightPlan line dashed
	/*var flightPlanLineSymbol = {
		path: 'M 0,-1 0,1',
		strokeOpacity: 1,
		scale: 4
	};*/

	// FLIGHTPLAN path
	var path_flightPlanLine = new google.maps.Polyline({
		//path: path_logCoordinates,
		strokeColor: "#FF0000",
		strokeOpacity: 1.0,
		strokeWeight: 2//,
		/*icons: [{
			icon: flightPlanLineSymbol,
			offset: '0',
			repeat: '20px'
		}]*/
	});

	path_flightPlanLine.setMap(map);
	path_flightPlan = path_flightPlanLine.getPath();
		
	// ETAG path
	var path_etagLine = new google.maps.Polyline({
		//path: path_logCoordinates,
		strokeColor: "#FFFF00",
		strokeOpacity: 1.0,
		strokeWeight: 2//,
		/*icons: [{
			icon: flightPlanLineSymbol,
			offset: '0',
			repeat: '20px'
		}]*/
	});

	path_etagLine.setMap(map);
	path_etag = path_etagLine.getPath();
}

function GUI_InitCircles() {

	// BOUNDARY BOX
	var boundaryboxOptions = {
		strokeColor: "#FF0000",
		strokeOpacity: 1.0,
		strokeWeight: 4,
		fillColor: "#FF0000",
		fillOpacity: 0.01,
		map: map,
		center: pos_homebase,
		radius: radius_boundarybox,
		clickable: false
	};
	boundaryboxCircle = new google.maps.Circle(boundaryboxOptions);

	// LAUNCH BOX
	var launchboxOptions = {
		strokeColor: "#0000FF",
		strokeOpacity: 0.8,
		strokeWeight: 4, 
		fillColor: "#0000FF",
		fillOpacity: 0.01,
		map: map,
		center: pos_homebase,
		radius: radius_launchbox,
		clickable: false
	};
	launchboxCircle = new google.maps.Circle(launchboxOptions);

	// SAFETY BOX
	var safetyboxOptions = {
		strokeColor: "#00FF00",
		strokeOpacity: 0.8,
		strokeWeight: 2,
		fillColor: "#00FF00",
		fillOpacity: 0.3,
		map: map,
		center:  pos_mid_safety_box,
		radius: radius_safetybox,
		clickable: false
	};
	safetyboxCircle = new google.maps.Circle(safetyboxOptions);

}

function GUI_PlaceLocMarker(loc) {
	if(gui_setWPClicked) {
		marker_clicked.setPosition(loc);

		//document.getElementById('clickedLat').value = loc.lat();
		document.getElementById('clickedWP').value = loc.toUrlValue(7);
		var lat_int = String(Math.round(loc.lat()*10000000));
		var lng_int = String(Math.round(loc.lng()*10000000));
		document.getElementById('clickedWP_int').value = lat_int + "," + lng_int;

		gui_setWPClicked = false;

		document.getElementById('setWPButton').value = "Set WP";
		document.getElementById('setWPButton').style.background = "#DDD";
	}
}

function GUI_SetWPClicked() {
	gui_setWPClicked = true;
	document.getElementById('setWPButton').value = "Click map!";
	document.getElementById('setWPButton').style.background = "#FF0000";
}

// Initialize Vexredus Tracker 
function init_vexredus_tracker() {
	// Initialize Google Maps div
	var mapDiv = document.getElementById('map_canvas');
	var mapOptions = {
		center: pos_esrange,
		zoom: 14,
		streetViewControl: false,
		mapTypeId: google.maps.MapTypeId.HYBRID
	};
	map = new google.maps.Map(mapDiv, mapOptions);

	// Initialize buttons
	GUI_InitButtons();

	// Initialize markers
	GUI_InitMarkers();

	// Init circles
	GUI_InitCircles();

	// Initialize mouse select position
	google.maps.event.addListener(map, 'click', function(event) {
		GUI_PlaceLocMarker(event.latLng);
	});

	marker_clicked = new google.maps.Marker({
		map: map,
		title: "User set WP"
	});
	
	// Initialize HTTP Telemetry 
	//HTTPTelemetry_Init();

	// Initialize LocalFile Controls
	LocalFile_Init();
}

